<template lang="pug">
.view.cp-manage-staff.fix-flex-pos
  //- 查询
  el-form.sf-search(:inline="true")
    el-form-item(label="一级部门 : ")
      el-select(v-model="oneLevelDept", placeholder="请选择", style="width: 120px", @change="changeTwoLevelDept")
        el-option(
          v-for="item in oneDeptSelectAll",
          :key="item.value", :label="item.name",
          :value="item.value")
    el-form-item(label="二级部门 : ")
      el-select(v-model="twoLevelDept", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in twoDeptSelectAll",
          :key="item.value", :label="item.name",
          :value="item.value")
    el-form-item(label="角色 : ")
      el-select(v-model="staffRole", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in staffRoleSelectAll",
          :key="item.value", :label="item.name",
          :value="item.value")
    el-form-item(label="在职状态 : ")
      el-select(v-model="workingStatus", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in workingStatusSelectAll",
          :key="item.value", :label="item.name",
          :value="item.value")
    el-form-item(label="账号状态 : ")
      el-select(v-model="accountStatus", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="item in accountStatusSelectAll",
          :key="item.value", :label="item.name",
          :value="item.value")
    el-form-item(label="搜索类型 : ")
      el-select(v-model="searchType", placeholder="请选择", style="width: 120px")
        el-option(
          v-for="(type, index) in searchTypeSelectAll",
          :key="index", :label="type",
          :value="index")
    el-form-item
      el-input(
        v-model="searchContent",
        placeholder="搜索内容",
        style="width: 200px")
    el-form-item
      el-button(type="primary", @click="searchStaffs") 搜索
    el-form-item
      el-button(type="primary", @click="resetSearch", plain) 重置
    el-form-item
      el-button(type="primary", @click="addStaff") 新建员工
  //- 列表
  .sf-table
    el-table(
      :data="staffList",
      highlight-current-row
      height="100%"
      size="mini"
      v-loading="loadingStaffs")
      el-table-column(align="center", show-overflow-tooltip, type="index", :index="indexMethod", label="序号", :fixed="true")
      el-table-column(align="center", show-overflow-tooltip, prop="name", label="姓名")
      el-table-column(align="center", show-overflow-tooltip, prop="employeeId", label="工号")
      el-table-column(align="center", show-overflow-tooltip, prop="sex", label="性别")
        template(slot-scope="scope")
          span {{ scope.row.sex | compare-list(sexSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="age", label="年龄")
      el-table-column(align="center", show-overflow-tooltip, prop="oneLevelDeptName", label="一级部门")
      el-table-column(align="center", show-overflow-tooltip, prop="twoLevelDeptName", label="二级部门")
      el-table-column(align="center", show-overflow-tooltip, prop="position", label="岗位")
        template(slot-scope="scope")
          span {{ scope.row.position | compare-list(comPositionSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="workingStatus", label="在职状态")
        template(slot-scope="scope")
          span {{ scope.row.workingStatus | compare-list(workingStatusSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="username", label="登录账号")
      el-table-column(align="center", show-overflow-tooltip, prop="roles", label="角色")
        template(slot-scope="scope")
          span {{ scope.row.roles | compare-arr(staffRoleSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="lastLoginDate", label="末次登录时间", min-width="100px")
        template(slot-scope="scope")
          span {{ scope.row.lastLoginDate | date-format }}
      el-table-column(align="center", show-overflow-tooltip, prop="accountStatus", label="账号状态")
        template(slot-scope="scope")
          span {{ scope.row.accountStatus | compare-list(accountStatusSelect) }}
      el-table-column(align="center", label="操作", min-width="120px")
        template(slot-scope="scope")
          el-tooltip(content="查看")
            i.icon-act.el-icon-view(@click="viewStaff(scope.row)")
          el-tooltip(content="编辑")
            i.icon-act.el-icon-edit(@click="eidtStaff(scope.row, scope.$index)")
          el-tooltip(content="删除")
            i.icon-act.el-icon-delete(@click="deleteStaff(scope.row, scope.$index)")
          el-tooltip(content="解锁", v-show="scope.row.accountStatus != 0")
            i.icon-act.el-icon-success(@click="changeStaffAccountStatus(scope.row)")
          el-tooltip(content="锁定", v-show="scope.row.accountStatus == 0")
            i.icon-act.el-icon-error(@click="changeStaffAccountStatus(scope.row)")
  //- 分页
  el-pagination.sf-pagination(
    layout="total, prev, pager, next, jumper",
    @current-change="changeStaffPage",
    :current-page.sync="currentPage",
    :page-size="pageSize",
    :total="staffListTotal")
  el-dialog.sf-dialog(
    :title="dialogTitle",
    :close-on-click-modal="viewStatus",
    :visible.sync="showDialog")
    .sf-pop-show(v-show="viewStatus")
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 姓名 】
          span(v-text="popupObj.name || '未知'")
        el-col(:span="12")
          strong 【 工号 】
          span(v-text="popupObj.employeeId || '未知'")
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 性别 】
          span {{ popupObj.sex | compare-list(sexSelect) }}
        el-col(:span="12")
          strong 【 生日 】
          span {{ popupObj.birthday | date-locale }}
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 手机 】
          span(v-text="popupObj.mobile || '未知'")
        el-col(:span="12")
          strong 【 年龄 】
          span(v-text="popupObj.age")
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 一级部门 】
          span {{ popupObj.oneLevelDeptName }}
          span.focus-manager(v-text="popupObj.isOneLevelManager ? '主管' : ''")
        el-col(:span="12")
          strong 【 二级部门 】
          span {{ popupObj.twoLevelDeptName }}
          span.focus-manager(v-text="popupObj.isTwoLevelManager ? '主管' : ''")
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 在职状态 】
          span {{ popupObj.workingStatus | compare-list(workingStatusSelect) }}
        el-col(:span="12")
          strong 【 岗位 】
          span {{ popupObj.position | compare-list(comPositionSelect) }}
      .sf-part-line
      el-row(:gutter="20")
        el-col(:span="12")
          strong 【 登录账号 】
          span(v-text="popupObj.username || '未知'")
      //- el-row(:gutter="20")
      //-   el-col(:span="12")
      //-     strong 【 登录密码 】
      //-     span(v-text="popupObj.password || '未知'")
      //-   el-col(:span="12")
      //-     strong 【 确认密码 】
      //-     span ********
      el-row(:gutter="20")
        el-col(:span="24")
          strong 【 角色 】
          span {{ popupObj.roles | compare-arr(staffRoleSelect) }}
      el-row(:gutter="20")
        el-col(:span="24")
          strong 【 账号状态 】
          span {{ popupObj.accountStatus | compare-list(accountStatusSelect) }}
    el-form.sf-pop-form(:inline="true", label-width="72px", v-show="!viewStatus")
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="姓名")
            el-input(v-model="popupObj.name", placeholder="姓名", :disabled="!addStatus && !viewStatus")
        el-col(:span="12")
          el-form-item.is-required(label="工号")
            el-input(v-model="popupObj.employeeId", placeholder="工号", :disabled="!addStatus && !viewStatus")
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="性别")
            el-radio(v-model="popupObj.sex", :label="0") 女
            el-radio(v-model="popupObj.sex", :label="1") 男
            el-radio(v-model="popupObj.sex", :label="2") 未知
        el-col(:span="12")
          el-form-item.is-required(label="生日")
            el-date-picker(v-model="popupObj.birthday", type="date",placeholder="选择日期", @change="generateBirth", :picker-options="pickerOption")
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="手机")
            el-input(v-model="popupObj.mobile", placeholder="手机")
        el-col(:span="12")
          el-form-item(label="年龄")
            el-input(:disabled="true", v-model="popupObj.age", placeholder="年龄")
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="一级部门")
            el-select(v-model="popupObj.oneLevelDept", placeholder="请选择", style="width: 64%", @change="changeTwoLevelDept")
              el-option(v-for="item in oneDeptSelect", :key="item.value", :label="item.name", :value="item.value")
            el-checkbox(v-model="popupObj.isOneLevelManager", style="marginLeft: 12px") 主管
        el-col(:span="12")
          el-form-item(label="二级部门")
            el-select(v-model="popupObj.twoLevelDept", placeholder="请选择", style="width: 64%")
              el-option(v-for="item in twoDeptSelect", :key="item.value", :label="item.name", :value="item.value")
            el-checkbox(v-model="popupObj.isTwoLevelManager", style="marginLeft: 12px") 主管
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="在职状态")
            el-select(v-model="popupObj.workingStatus", placeholder="请选择", style="width: 64%")
              el-option(
                v-for="item in workingStatusSelect",
                :key="item.value", :label="item.name",
                :value="item.value")
        el-col(:span="12")
          el-form-item.is-required(label="岗位")
            el-select(v-model="popupObj.position", placeholder="请选择")
              el-option(v-for="item in comPositionSelect", :key="item.value", :label="item.name", :value="item.value")
      .sf-part-line
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="登录账号")
            el-input(v-model="popupObj.username", placeholder="登录账号", :disabled="!addStatus && !viewStatus")
      el-row(:gutter="36", v-show="!modifyPass",)
        el-col(:span="24")
          el-form-item(label="登录密码")
            el-button(type="primary", plain, @click="modifyPass=true", size="mini") 修改密码
      el-row(:gutter="36", v-show="modifyPass")
        el-col(:span="8")
          el-form-item.is-required(label="登录密码")
            el-input(v-model="popupObj.password", type="password", placeholder="登录密码")
        el-col(:span="8")
          el-form-item.is-required(label="确认密码")
            el-input(v-model="popupObj.passwordAgain", type="password", placeholder="确认密码")
        el-col(:span="8")
          el-button(:disabled="addStatus", type="primary", plain, @click="modifyPass=false", size="mini") 取消修改
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="角色")
            el-select(v-model="popupObj.roles" multiple collapse-tags placeholder="请选择")
              el-option(v-for="item in staffRoleSelect", :key="item.value", :label="item.name", :value="item.value")
      el-row(:gutter="36")
        el-col(:span="12")
          el-form-item.is-required(label="账号状态")
            el-radio(v-model="popupObj.accountStatus", :label="0") 激活
            el-radio(v-model="popupObj.accountStatus", :label="1") 锁定
    el-row(v-show="!viewStatus")
      el-col(:span="24", style="text-align: center;")
        el-button(type="primary", style="width: 80px;", plain, @click="closeDialog") 取消
        el-button(type="primary", style="width: 80px; margin-left: 40px;", @click="saveStaff") 确定
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import ManApi from '@/api/manage';
import { getAge } from '@/utils/date';
import validate from '@/utils/validate';
import check from './check';

const { isEmpty } = validate;

export default {
  name: 'manstaff',
  data() {
    return {
      // search
      oneLevelDept: null,
      twoLevelDept: null,
      staffRole: null,
      workingStatus: null,
      accountStatus: null,
      searchType: 0,
      searchContent: '',
      // table
      staffList: [],
      staffListTotal: 1,
      loadingStaffs: true,
      currentPage: 1,
      pageSize: 20,
      // 弹层
      dialogTitle: '',
      showDialog: false,
      addStatus: false,
      viewStatus: true,
      popupObj: {
        roles: []
      },
      modifyPass: false,
      // select list
      twoDeptSelect: [],
      twoDeptSelectAll: [{ name: '全部', value: null }],
      staffRoleSelect: [],
      staffRoleSelectAll: [],
      //
      workingStatusSelect: [
        { name: '在职', value: 0 },
        { name: '离职', value: 1 }
      ],
      workingStatusSelectAll: [
        { name: '全部', value: null },
        { name: '在职', value: 0 },
        { name: '离职', value: 1 }
      ],
      accountStatusSelect: [
        { name: '激活', value: 0 },
        { name: '锁定', value: 1 }
      ],
      accountStatusSelectAll: [
        { name: '全部', value: null },
        { name: '激活', value: 0 },
        { name: '锁定', value: 1 }
      ],
      searchTypeSelectAll: ['员工姓名', '员工号', '手机号', '登录账号'],
      sexSelect: [
        { name: '女', value: 0 },
        { name: '男', value: 1 },
        { name: '未知', value: 2 }
      ],
      pickerOption: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      }
    };
  },
  computed: {
    ...mapGetters(['oneDeptSelect', 'oneDeptSelectAll', 'comPositionSelect'])
  },
  methods: {
    indexMethod (i) {
      const size = this.pageSize || 20;
      return ((this.currentPage - 1) * size) + (i + 1);
    },
    openDialog () {
      this.showDialog = true;
    },
    closeDialog () {
      this.showDialog = false;
    },
    changeTwoLevelDept (oneLevelDept) {
      ComApi.getTwoLevelDept({ oneLevelDept }).then((twoDept) => {
        // 重置
        this.twoLevelDept = null;
        this.popupObj.twoLevelDept = null;

        this.twoDeptSelect = twoDept;
        this.twoDeptSelectAll = [{ name: '全部', value: null }].concat(twoDept);
      });
    },
    makeSearch () {
      const params = {};
      const searchTypeIndex = parseInt(this.searchType, 10);
      if (this.oneLevelDept) {
        params.oneLevelDept = this.oneLevelDept;
      }
      if (this.twoLevelDept) {
        params.twoLevelDept = this.twoLevelDept;
      }
      if (this.staffRole) {
        params.roleId = this.staffRole;
      }
      if (typeof this.workingStatus !== 'object') {
        params.workingStatus = this.workingStatus;
      }
      if (typeof this.accountStatus !== 'object') {
        params.accountStatus = this.accountStatus;
      }

      const props = ['name', 'employeeId', 'mobile', 'username'];
      if (this.searchContent) {
        params[props[searchTypeIndex]] = this.searchContent;
      }

      return params;
    },
    resetSearch () {
      this.oneLevelDept = null;
      this.twoLevelDept = null;
      this.staffRole = null;
      this.workingStatus = null;
      this.accountStatus = null;
      this.searchType = 0;
      this.searchContent = '';
    },
    searchStaffs () {
      const params = this.makeSearch();
      this.loadingStaffs = true;
      ManApi.getStaffList(params).then((result) => {
        if (!result.status) {
          this.staffList = result.obj.records;
          this.staffListTotal = result.obj.totalNum;
          this.currentPage = 1;
          this.$message.success('刷新成功');
        } else {
          this.staffList = [];
          this.staffListTotal = 1;
          this.$message.error(result.comment);
        }
        this.loadingStaffs = false;
      }).catch((error) => {
        this.loadingStaffs = false;
        console.log(JSON.stringify(error));
      });
    },
    // 监听对Staff条目操作事件
    addStaff () {
      this.dialogTitle = '新建员工';
      this.addStatus = true;
      this.viewStatus = false;
      this.modifyPass = true;
      this.popupObj = {
        roles: [],
        oneLevelDept: null,
        twoLevelDept: null
      };
      this.twoDeptSelect = [];
      this.openDialog();
    },
    viewStaff (row) {
      this.dialogTitle = '查看员工详情';
      this.addStatus = false;
      this.viewStatus = true;
      this.modifyPass = false;
      ManApi.getStaffDetail({ id: row.employeeId }).then((result) => {
        if (!result.status) {
          this.popupObj = result.obj;
          this.openDialog();
          const oneLevelDept = result.obj.oneLevelDept;
          ComApi.getTwoLevelDept({ oneLevelDept }).then((twoDeptSelect) => {
            this.twoDeptSelect = twoDeptSelect;
          });
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    eidtStaff (row, index) {
      this.dialogTitle = '编辑员工详情';
      this.focusIndex = index;
      this.addStatus = false;
      this.viewStatus = false;
      this.modifyPass = false;
      ManApi.getStaffDetail({ id: row.employeeId }).then((result) => {
        if (!result.status) {
          this.popupObj = result.obj;
          this.openDialog();
          const oneLevelDept = result.obj.oneLevelDept;
          ComApi.getTwoLevelDept({ oneLevelDept }).then((twoDeptSelect) => {
            this.twoDeptSelect = twoDeptSelect;
          });
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    deleteStaff (row, index) {
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingStaffs = true;
        ManApi.deleteStaff({ id: row.employeeId }).then((result) => {
          this.loadingStaffs = false;
          if (!result.status) {
            this.staffList.splice(index, 1);
            this.staffListTotal = this.staffListTotal - 1;
            this.$message.success('删除成功');
          } else {
            this.$message.error(`删除失败：${result.comment}`);
          }
        }).catch((error) => {
          console.log(JSON.stringify(error));
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    saveStaff () {
      // 处理登录密码
      if (this.modifyPass) {
        const { username, password, passwordAgain } = this.popupObj;
        if (isEmpty(password) || isEmpty(passwordAgain)) {
          this.$message.error('登录密码不能为空');
          return false;
        } else {
          this.popupObj.username = username.trim();
          this.popupObj.password = password.trim();
          this.popupObj.passwordAgain = passwordAgain.trim();
        }
      }
      const canSave = check(this.popupObj, this.modifyPass);
      if (canSave) {
        ManApi.saveStaff(this.popupObj).then((result) => {
          if (!result.status) {
            this.$message.success('保存成功');
            if (this.popupObj.serialNo) {
              this.$set(this.staffList, this.focusIndex, result.obj);
            } else {
              this.staffList.unshift({});
              this.$set(this.staffList, 0, result.obj);
              this.staffListTotal += 1;
              if (this.staffListTotal > 20) {
                this.staffList.pop();
              }
            }
            this.closeDialog();
          } else {
            this.$message.error(`保存失败：${result.comment}`);
          }
        }).catch((error) => {
          this.closeDialog();
          console.log(JSON.stringify(error));
        });
      }
    },
    changeStaffAccountStatus (row) {
      const username = row.username;
      ManApi.changeStaffAccountStatus({ username }).then((result) => {
        if (!result.status) {
          row.accountStatus = row.accountStatus ? 0 : 1;
          this.$message.success('变更成功');
        } else {
          this.$message.error(`变更失败：${result.comment}`);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    // 监听计划翻页
    changeStaffPage (currentPage) {
      const params = this.makeSearch();
      params.pageNum = currentPage;
      this.loadingStaffs = true;
      ManApi.getStaffList(params).then((result) => {
        if (!result.status) {
          this.staffList = result.obj.records;
          this.staffListTotal = result.obj.totalNum;
          this.currentPage = currentPage;
        } else {
          this.$message.error(result.comment);
        }
        this.loadingStaffs = false;
      }).catch((error) => {
        this.loadingStaffs = false;
        console.log(JSON.stringify(error));
      });
    },
    generateBirth () {
      const birth = this.popupObj.birthday;
      this.popupObj.age = getAge(birth);
    }
  },
  beforeRouteEnter (to, from, next) {
    next();
  },
  created () {
    // 取得角色列表
    ManApi.getRoleList().then((result) => {
      if (!result.status) {
        const roleList = result.obj;
        this.staffRoleSelect = roleList.map(role => ({
          name: role.roleName,
          value: role.id
        }));
        this.staffRoleSelectAll = [{ name: '全部', value: null }].concat(this.staffRoleSelect);
      }
    });
  },
  mounted () {
    ManApi.getStaffList().then((result) => {
      if (!result.status) {
        this.staffList = result.obj.records;
        this.staffListTotal = result.obj.totalNum;
      } else {
        this.$message.error(result.comment);
      }
      this.loadingStaffs = false;
    }).catch((error) => {
      this.loadingStaffs = false;
      console.log(JSON.stringify(error));
    });
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
$SEARCHHEIGHT: 104px
$PAGEHEIGHT: 56px
.cp-manage-staff
  .sf-search
    height: $SEARCHHEIGHT
    overflow-x: auto
    overflow-y: hidden
    padding: 12px 0 12px 16px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      padding-right: 6px
  .sf-table
    position: absolute
    top: $SEARCHHEIGHT
    bottom: $PAGEHEIGHT
    left: 16px
    right: 16px
    overflow: auto
    table
      &::before
        display: none
      .icon-act
        font-size: 16px
        margin-left: 3px
        margin-right: 3px
  .sf-pagination
    position: absolute
    bottom: 12px
    left: 0
    right: 0
    text-align: center
  .el-dialog__body
    padding: 24px 36px 28px 40px
  .sf-pop-show
    padding: 4px 16px
    .el-row
      margin-bottom: 12px
      &:nth-child(odd)
        background: #f5f5f5
      &:nth-child(even)
        background: beige
    strong
      display: inline-block
      font-weight: 400
      margin-right: 8px
    .focus-manager
      color: red
      margin-left: 8px
  .sf-pop-form
    .el-form-item
      width: 100%
      margin-right: 0
    .el-form-item__content
      width: calc(100% - 72px)
      .el-date-editor.el-input, .el-date-editor.el-input__inner
        width: 100%
    .el-form-item__label
      text-align: left
    .el-select
      width: 100%
  .sf-part-line
    border-top: 1px solid #dcdfe6
    margin-bottom: 15px
</style>
